home *** CD-ROM | disk | FTP | other *** search
/ Celestin Apprentice 7 / Apprentice-Release7.iso / Source Code / C / Applications / Moscow ML 1.42 / src / mosmllib / PP.sml < prev    next >
Encoding:
Text File  |  1997-08-18  |  20.1 KB  |  596 lines  |  [TEXT/R*ch]

  1. (* PP -- Oppen-style prettyprinters.
  2.  *
  3.  * Modified for Moscow ML from SML/NJ Library version 0.2
  4.  *
  5.  * COPYRIGHT (c) 1992 by AT&T Bell Laboratories.
  6.  * See file mosml/copyrght/copyrght.att for details.
  7.  *)
  8.  
  9. (* the functions and data for actually doing printing. *)
  10.  
  11. open Array 
  12. infix 9 sub
  13.  
  14. (* the queue library, formerly in unit Ppqueue *)
  15.  
  16. datatype Qend = Qback | Qfront
  17.  
  18. exception QUEUE_FULL
  19. exception QUEUE_EMPTY
  20. exception REQUESTED_QUEUE_SIZE_TOO_SMALL
  21.  
  22. local 
  23.     fun ++ i n = (i + 1) mod n
  24.     fun -- i n = (i - 1) mod n
  25. in
  26.  
  27. abstype 'a queue = QUEUE of {elems: 'a array, (* the contents *)
  28.                              front: int ref,
  29.                              back: int ref,
  30.                              size: int}  (* fixed size of element array *)
  31. with
  32.  
  33.   fun is_empty (QUEUE{front=ref ~1, back=ref ~1,...}) = true
  34.     | is_empty _ = false
  35.  
  36.   fun mk_queue n init_val =
  37.       if (n < 2)
  38.       then raise REQUESTED_QUEUE_SIZE_TOO_SMALL
  39.       else QUEUE{elems=array(n, init_val), front=ref ~1, back=ref ~1, size=n}
  40.  
  41.   fun clear_queue (QUEUE{front,back,...}) = (front := ~1; back := ~1)
  42.  
  43.   fun queue_at Qfront (QUEUE{elems,front,...}) = elems sub !front
  44.     | queue_at Qback (QUEUE{elems,back,...}) = elems sub !back
  45.  
  46.   fun en_queue Qfront item (Q as QUEUE{elems,front,back,size}) =
  47.         if (is_empty Q)
  48.         then (front := 0; back := 0;
  49.               update(elems,0,item))
  50.         else let val i = --(!front) size
  51.              in  if (i = !back)
  52.                  then raise QUEUE_FULL
  53.                  else (update(elems,i,item); front := i)
  54.              end
  55.     | en_queue Qback item (Q as QUEUE{elems,front,back,size}) =
  56.         if (is_empty Q)
  57.         then (front := 0; back := 0;
  58.               update(elems,0,item))
  59.         else let val i = ++(!back) size
  60.              in  if (i = !front)
  61.                  then raise QUEUE_FULL
  62.                  else (update(elems,i,item); back := i)
  63.              end
  64.  
  65.   fun de_queue Qfront (Q as QUEUE{front,back,size,...}) =
  66.         if (!front = !back) (* unitary queue *)
  67.         then clear_queue Q
  68.         else front := ++(!front) size
  69.     | de_queue Qback (Q as QUEUE{front,back,size,...}) =
  70.         if (!front = !back)
  71.         then clear_queue Q
  72.         else back := --(!back) size
  73.  
  74. end (* abstype queue *)
  75. end (* local   *)
  76.  
  77.  
  78. prim_val magic : 'a -> 'b = 1 "identity";
  79.  
  80. (* exception PP_FAIL of string *)
  81.  
  82. datatype break_style = CONSISTENT | INCONSISTENT
  83.  
  84. datatype break_info
  85.   = FITS
  86.   | PACK_ONTO_LINE of int
  87.   | ONE_PER_LINE of int
  88.  
  89. (* Some global values *)
  90. val INFINITY = 999999
  91.  
  92. abstype indent_stack = Istack of break_info list ref
  93. with
  94.   fun mk_indent_stack() = Istack (ref([]:break_info list))
  95.   fun clear_indent_stack (Istack stk) = (stk := ([]:break_info list))
  96.   fun top (Istack stk) =
  97.       case !stk
  98.         of nil => raise Fail "PP-error: top: badly formed block"
  99.      | x::_ => x
  100.   fun push (x,(Istack stk)) = stk := x::(!stk)
  101.   fun pop (Istack stk) =
  102.       case !stk
  103.         of nil => raise Fail "PP-error: pop: badly formed block"
  104.      | _::rest => stk := rest
  105. end
  106.  
  107. (* The delim_stack is used to compute the size of blocks. It is
  108.    a stack of indices into the token buffer. The indices only point to
  109.    BBs, Es, and BRs. We push BBs and Es onto the stack until a BR
  110.    is encountered. Then we compute sizes and pop. When we encounter
  111.    a BR in the middle of a block, we compute the Distance_to_next_break
  112.    of the previous BR in the block, if there was one.
  113.  
  114.    We need to be able to delete from the bottom of the delim_stack, so
  115.    we use a queue, treated with a stack discipline, i.e., we only add
  116.    items at the head of the queue, but can delete from the front or
  117.    back of the queue.
  118. *)
  119. abstype delim_stack = Dstack of int queue
  120. with
  121.   fun new_delim_stack i = Dstack(mk_queue i ~1)
  122.   fun reset_delim_stack (Dstack q) = clear_queue q
  123.  
  124.   fun pop_delim_stack (Dstack d) = de_queue Qfront d
  125.   fun pop_bottom_delim_stack (Dstack d) = de_queue Qback d
  126.  
  127.   fun push_delim_stack(i,Dstack d) = en_queue Qfront i d
  128.   fun top_delim_stack (Dstack d) = queue_at Qfront d
  129.   fun bottom_delim_stack (Dstack d) = queue_at Qback d
  130.   fun delim_stack_is_empty (Dstack d) = is_empty d
  131. end
  132.  
  133.  
  134. type block_info = { Block_size : int ref,
  135.                     Block_offset : int,
  136.                     How_to_indent : break_style }
  137.  
  138.  
  139. (* Distance_to_next_break includes Number_of_blanks. Break_offset is
  140.    a local offset for the break. BB represents a sequence of contiguous
  141.    Begins. E represents a sequence of contiguous Ends.
  142. *)
  143. datatype pp_token
  144.   = S of  {String : string, Length : int}
  145.   | BB of {Pblocks : block_info list ref,   (* Processed   *)
  146.            Ublocks : block_info list ref}  (* Unprocessed *)
  147.   | E of  {Pend : int ref, Uend : int ref}
  148.   | BR of {Distance_to_next_break : int ref,
  149.            Number_of_blanks : int,
  150.            Break_offset : int}
  151.  
  152.  
  153. (* The initial values in the token buffer *)
  154. val initial_token_value = S{String = "", Length = 0}
  155.  
  156. (* type ppstream = General.ppstream; *)
  157. datatype ppstream_ =
  158.   PPS of
  159.      {consumer : string -> unit,
  160.       linewidth : int,
  161.       flush : unit -> unit,
  162.       the_token_buffer : pp_token array,
  163.       the_delim_stack : delim_stack,
  164.       the_indent_stack : indent_stack,
  165.       ++ : int ref -> unit,    (* increment circular buffer index *)
  166.       space_left : int ref,    (* remaining columns on page *)
  167.       left_index : int ref,    (* insertion index *)
  168.       right_index : int ref,   (* output index *)
  169.       left_sum : int ref,      (* size of strings and spaces inserted *)
  170.       right_sum : int ref}     (* size of strings and spaces printed *)
  171.  
  172.  
  173. type ppconsumer = {consumer : string -> unit,
  174.            linewidth : int,
  175.            flush : unit -> unit}
  176.  
  177. fun mk_ppstream {consumer,linewidth,flush} =
  178.     if (linewidth<5)
  179.     then raise Fail "PP-error: linewidth too_small"
  180.     else let val buf_size = 3*linewidth
  181.           in magic(
  182.              PPS{consumer = consumer,
  183.          linewidth = linewidth,
  184.          flush = flush,
  185.          the_token_buffer = array(buf_size, initial_token_value),
  186.          the_delim_stack = new_delim_stack buf_size,
  187.          the_indent_stack = mk_indent_stack (),
  188.          ++ = fn i => i := ((!i + 1) mod buf_size),
  189.          space_left = ref linewidth,
  190.          left_index = ref 0, right_index = ref 0,
  191.          left_sum = ref 0, right_sum = ref 0}
  192.                  ) : ppstream
  193.      end
  194.  
  195. fun dest_ppstream(pps : ppstream) =
  196.   let val PPS{consumer,linewidth,flush, ...} = magic pps
  197.   in {consumer=consumer,linewidth=linewidth,flush=flush} end
  198.  
  199. local
  200.   val space = " "
  201.   fun mk_space (0,s) = String.concat s
  202.     | mk_space (n,s) = mk_space((n-1), (space::s))
  203.   val space_table = Vector.tabulate(100, fn i => mk_space(i,[]))
  204.   fun nspaces n = Vector.sub(space_table, n)
  205.       handle General.Subscript =>
  206.     if n < 0
  207.     then ""
  208.     else let val n2 = n div 2
  209.          val n2_spaces = nspaces n2
  210.          val extra = if (n = (2*n2)) then "" else space
  211.               in String.concat [n2_spaces, n2_spaces, extra]
  212.          end
  213. in
  214.   fun cr_indent (ofn, i) = ofn ("\n"^(nspaces i))
  215.   fun indent (ofn,i) = ofn (nspaces i)
  216. end
  217.  
  218.  
  219. (* Print a the first member of a contiguous sequence of Begins. If there
  220.    are "processed" Begins, then take the first off the list. If there are
  221.    no processed Begins, take the last member off the "unprocessed" list.
  222.    This works because the unprocessed list is treated as a stack, the
  223.    processed list as a FIFO queue. How can an item on the unprocessed list
  224.    be printable? Because of what goes on in add_string. See there for details.
  225. *)
  226.  
  227. fun print_BB (_,{Pblocks = ref [], Ublocks = ref []}) =
  228.              raise Fail "PP-error: print_BB"
  229.   | print_BB (PPS{the_indent_stack,linewidth,space_left=ref sp_left,...},
  230.              {Pblocks as ref({How_to_indent=CONSISTENT,Block_size,
  231.                               Block_offset}::rst),
  232.               Ublocks=ref[]}) =
  233.        (push ((if (!Block_size > sp_left)
  234.                then ONE_PER_LINE (linewidth - (sp_left - Block_offset))
  235.                else FITS),
  236.           the_indent_stack);
  237.         Pblocks := rst)
  238.   | print_BB(PPS{the_indent_stack,linewidth,space_left=ref sp_left,...},
  239.              {Pblocks as ref({Block_size,Block_offset,...}::rst),Ublocks=ref[]}) =
  240.        (push ((if (!Block_size > sp_left)
  241.                then PACK_ONTO_LINE (linewidth - (sp_left - Block_offset))
  242.                else FITS),
  243.           the_indent_stack);
  244.         Pblocks := rst)
  245.   | print_BB (PPS{the_indent_stack, linewidth, space_left=ref sp_left,...},
  246.               {Ublocks,...}) =
  247.       let fun pr_end_Ublock [{How_to_indent=CONSISTENT,Block_size,Block_offset}] l =
  248.         (push ((if (!Block_size > sp_left)
  249.             then ONE_PER_LINE (linewidth - (sp_left - Block_offset))
  250.             else FITS),
  251.                the_indent_stack);
  252.                  List.rev l)
  253.         | pr_end_Ublock [{Block_size,Block_offset,...}] l =
  254.         (push ((if (!Block_size > sp_left)
  255.             then PACK_ONTO_LINE (linewidth - (sp_left - Block_offset))
  256.             else FITS),
  257.                the_indent_stack);
  258.                  List.rev l)
  259.         | pr_end_Ublock (a::rst) l = pr_end_Ublock rst (a::l)
  260.             | pr_end_Ublock _ _ =
  261.                 raise Fail "PP-error: print_BB: internal error"
  262.        in Ublocks := pr_end_Ublock(!Ublocks) []
  263.       end
  264.  
  265.  
  266. (* Uend should always be 0 when print_E is called. *)
  267. fun print_E (_,{Pend = ref 0, Uend = ref 0}) =
  268.       raise Fail "PP-error: print_E"
  269.   | print_E (istack,{Pend, ...}) =
  270.       let fun pop_n_times 0 = ()
  271.         | pop_n_times n = (pop istack; pop_n_times(n-1))
  272.        in pop_n_times(!Pend); Pend := 0
  273.       end
  274.  
  275.  
  276. (* "cursor" is how many spaces across the page we are. *)
  277.  
  278. fun print_token(PPS{consumer,space_left,...}, S{String,Length}) =
  279.       (consumer String;
  280.        space_left := (!space_left) - Length)
  281.   | print_token(ppstrm,BB b) = print_BB(ppstrm,b)
  282.   | print_token(PPS{the_indent_stack,...},E e) =
  283.       print_E (the_indent_stack,e)
  284.   | print_token (PPS{the_indent_stack,space_left,consumer,linewidth,...},
  285.                  BR{Distance_to_next_break,Number_of_blanks,Break_offset}) =
  286.      (case (top the_indent_stack)
  287.         of FITS =>
  288.          (space_left := (!space_left) - Number_of_blanks;
  289.               indent (consumer,Number_of_blanks))
  290.          | (ONE_PER_LINE cursor) =>
  291.              let val new_cursor = cursor + Break_offset
  292.               in space_left := linewidth - new_cursor;
  293.                  cr_indent (consumer,new_cursor)
  294.          end
  295.          | (PACK_ONTO_LINE cursor) =>
  296.          if (!Distance_to_next_break > (!space_left))
  297.          then let val new_cursor = cursor + Break_offset
  298.            in space_left := linewidth - new_cursor;
  299.               cr_indent(consumer,new_cursor)
  300.           end
  301.          else (space_left := !space_left - Number_of_blanks;
  302.            indent (consumer,Number_of_blanks)))
  303.  
  304.  
  305. fun clear_ppstream(pps : ppstream) =
  306.     let val PPS{the_token_buffer, the_delim_stack,
  307.                 the_indent_stack,left_sum, right_sum,
  308.                 left_index, right_index,space_left,linewidth,...}
  309.               = magic pps
  310.         val buf_size = 3*linewidth
  311.     fun set i =
  312.         if (i = buf_size)
  313.         then ()
  314.         else (update(the_token_buffer,i,initial_token_value);
  315.           set (i+1))
  316.      in set 0;
  317.     clear_indent_stack the_indent_stack;
  318.     reset_delim_stack the_delim_stack;
  319.     left_sum := 0; right_sum := 0;
  320.     left_index := 0; right_index := 0;
  321.     space_left := linewidth
  322.     end
  323.  
  324.  
  325. (* Move insertion head to right unless adding a BB and already at a BB,
  326.    or unless adding an E and already at an E.
  327. *)
  328. fun BB_inc_right_index(PPS{the_token_buffer, right_index, ++,...})=
  329.     case (the_token_buffer sub (!right_index))
  330.       of (BB _) => ()
  331.        | _ => ++right_index
  332.  
  333. fun E_inc_right_index(PPS{the_token_buffer,right_index, ++,...})=
  334.     case (the_token_buffer sub (!right_index))
  335.       of (E _) => ()
  336.        | _ => ++right_index
  337.  
  338.  
  339. fun pointers_coincide(PPS{left_index,right_index,the_token_buffer,...}) =
  340.     (!left_index = !right_index) andalso
  341.     (case (the_token_buffer sub (!left_index))
  342.        of (BB {Pblocks = ref [], Ublocks = ref []}) => true
  343.     | (BB _) => false
  344.     | (E {Pend = ref 0, Uend = ref 0}) => true
  345.     | (E _) => false
  346.     | _ => true)
  347.  
  348. fun advance_left (ppstrm as PPS{consumer,left_index,left_sum,
  349.                                 the_token_buffer,++,...},
  350.                   instr) =
  351.     let val NEG = ~1
  352.     val POS = 0
  353.     fun inc_left_sum (BR{Number_of_blanks, ...}) =
  354.          left_sum := (!left_sum) + Number_of_blanks
  355.       | inc_left_sum (S{Length, ...}) = left_sum := (!left_sum) + Length
  356.       | inc_left_sum _ = ()
  357.  
  358.     fun last_size [{Block_size, ...}:block_info] = !Block_size
  359.       | last_size (_::rst) = last_size rst
  360.           | last_size _ = raise Fail "PP-error: last_size: internal error"
  361.     fun token_size (S{Length, ...}) = Length
  362.       | token_size (BB b) =
  363.          (case b
  364.                 of {Pblocks = ref [], Ublocks = ref []} =>
  365.                      raise Fail "PP-error: BB_size"
  366.              | {Pblocks as ref(_::_),Ublocks=ref[]} => POS
  367.          | {Ublocks, ...} => last_size (!Ublocks))
  368.       | token_size (E{Pend = ref 0, Uend = ref 0}) =
  369.               raise Fail "PP-error: token_size.E"
  370.       | token_size (E{Pend = ref 0, ...}) = NEG
  371.       | token_size (E _) = POS
  372.       | token_size (BR {Distance_to_next_break, ...}) = !Distance_to_next_break
  373.     fun loop (instr) =
  374.         if (token_size instr < 0)  (* synchronization point; cannot advance *)
  375.         then ()
  376.         else (print_token(ppstrm,instr);
  377.           inc_left_sum instr;
  378.           if (pointers_coincide ppstrm)
  379.           then ()
  380.           else (* increment left index *)
  381.  
  382.     (* When this is evaluated, we know that the left_index has not yet
  383.        caught up to the right_index. If we are at a BB or an E, we can
  384.        increment left_index if there is no work to be done, i.e., all Begins
  385.        or Ends have been dealt with. Also, we should do some housekeeping and
  386.        clear the buffer at left_index, otherwise we can get errors when
  387.        left_index catches up to right_index and we reset the indices to 0.
  388.        (We might find ourselves adding a BB to an "old" BB, with the result
  389.        that the index is not pushed onto the delim_stack. This can lead to
  390.        mangled output.)
  391.     *)
  392.                (case (the_token_buffer sub (!left_index))
  393.               of (BB {Pblocks = ref [], Ublocks = ref []}) =>
  394.                    (update(the_token_buffer,!left_index,
  395.                        initial_token_value);
  396.                 ++left_index)
  397.                | (BB _) => ()
  398.                | (E {Pend = ref 0, Uend = ref 0}) =>
  399.                    (update(the_token_buffer,!left_index,
  400.                        initial_token_value);
  401.                 ++left_index)
  402.                | (E _) => ()
  403.                | _ => ++left_index;
  404.             loop (the_token_buffer sub (!left_index))))
  405.      in loop instr
  406.     end
  407.  
  408.  
  409. fun begin_block (pps : ppstream) style offset =
  410.   let val ppstrm = magic pps : ppstream_
  411.       val PPS{the_token_buffer, the_delim_stack,left_index,
  412.               left_sum, right_index, right_sum,...}
  413.             = ppstrm
  414.   in
  415.    (if (delim_stack_is_empty the_delim_stack)
  416.     then (left_index := 0;
  417.       left_sum := 1;
  418.       right_index := 0;
  419.       right_sum := 1)
  420.     else BB_inc_right_index ppstrm;
  421.     case (the_token_buffer sub (!right_index))
  422.       of (BB {Ublocks, ...}) =>
  423.        Ublocks := {Block_size = ref (~(!right_sum)),
  424.                Block_offset = offset,
  425.                How_to_indent = style}::(!Ublocks)
  426.        | _ => (update(the_token_buffer, !right_index,
  427.               BB{Pblocks = ref [],
  428.              Ublocks = ref [{Block_size = ref (~(!right_sum)),
  429.                      Block_offset = offset,
  430.                      How_to_indent = style}]});
  431.            push_delim_stack (!right_index, the_delim_stack)))
  432.   end
  433.  
  434. fun end_block(pps : ppstream) =
  435.   let val ppstrm = magic pps : ppstream_
  436.       val PPS{the_token_buffer,the_delim_stack,right_index,...}
  437.             = ppstrm
  438.   in
  439.     if (delim_stack_is_empty the_delim_stack)
  440.     then print_token(ppstrm,(E{Pend = ref 1, Uend = ref 0}))
  441.     else (E_inc_right_index ppstrm;
  442.       case (the_token_buffer sub (!right_index))
  443.             of (E{Uend, ...}) => Uend := !Uend + 1
  444.          | _ => (update(the_token_buffer,!right_index,
  445.                 E{Uend = ref 1, Pend = ref 0});
  446.              push_delim_stack (!right_index, the_delim_stack)))
  447.   end
  448.  
  449. local
  450.   fun check_delim_stack(PPS{the_token_buffer,the_delim_stack,right_sum,...}) =
  451.       let fun check k =
  452.           if (delim_stack_is_empty the_delim_stack)
  453.           then ()
  454.           else case(the_token_buffer sub (top_delim_stack the_delim_stack))
  455.              of (BB{Ublocks as ref ((b as {Block_size, ...})::rst),
  456.                 Pblocks}) =>
  457.                if (k>0)
  458.                then (Block_size := !right_sum + !Block_size;
  459.                  Pblocks := b :: (!Pblocks);
  460.                  Ublocks := rst;
  461.                  if (List.length rst = 0)
  462.                  then pop_delim_stack the_delim_stack
  463.                  else ();
  464.                  check(k-1))
  465.                else ()
  466.               | (E{Pend,Uend}) =>
  467.                (Pend := (!Pend) + (!Uend);
  468.                 Uend := 0;
  469.                 pop_delim_stack the_delim_stack;
  470.                 check(k + !Pend))
  471.               | (BR{Distance_to_next_break, ...}) =>
  472.                (Distance_to_next_break :=
  473.                   !right_sum + !Distance_to_next_break;
  474.                 pop_delim_stack the_delim_stack;
  475.                 if (k>0)
  476.                 then check k
  477.                 else ())
  478.                       | _ => raise Fail "PP-error: check_delim_stack.catchall"
  479.        in check 0
  480.       end
  481. in
  482.  
  483.   fun add_break (pps : ppstream) (n, break_offset) =
  484.     let val ppstrm = magic pps : ppstream_
  485.         val PPS{the_token_buffer,the_delim_stack,left_index,
  486.                 right_index,left_sum,right_sum, ++, ...}
  487.               = ppstrm
  488.     in
  489.       (if (delim_stack_is_empty the_delim_stack)
  490.        then (left_index := 0; right_index := 0;
  491.          left_sum := 1;   right_sum := 1)
  492.        else ++right_index;
  493.        update(the_token_buffer, !right_index,
  494.           BR{Distance_to_next_break = ref (~(!right_sum)),
  495.          Number_of_blanks = n,
  496.          Break_offset = break_offset});
  497.        check_delim_stack ppstrm;
  498.        right_sum := (!right_sum) + n;
  499.        push_delim_stack (!right_index,the_delim_stack))
  500.     end
  501.  
  502.   fun flush_ppstream0(pps : ppstream) =
  503.     let val ppstrm = magic pps : ppstream_
  504.         val PPS{the_delim_stack,the_token_buffer, flush, left_index,...}
  505.               = ppstrm
  506.     in
  507.       (if (delim_stack_is_empty the_delim_stack)
  508.        then ()
  509.        else (check_delim_stack ppstrm;
  510.          advance_left(ppstrm, the_token_buffer sub (!left_index)));
  511.        flush())
  512.     end
  513.  
  514. end (* local *)
  515.  
  516.  
  517. fun flush_ppstream ppstrm =
  518.     (flush_ppstream0 ppstrm;
  519.      clear_ppstream ppstrm)
  520.  
  521. fun add_string (pps : ppstream) s =
  522.     let val ppstrm = magic pps : ppstream_
  523.         val PPS{the_token_buffer,the_delim_stack,consumer,
  524.                 right_index,right_sum,left_sum,
  525.                 left_index,space_left,++,...}
  526.               = ppstrm
  527.         fun fnl [{Block_size, ...}:block_info] = Block_size := INFINITY
  528.       | fnl (_::rst) = fnl rst
  529.           | fnl _ = raise Fail "PP-error: fnl: internal error"
  530.  
  531.     fun set(dstack,BB{Ublocks as ref[{Block_size,...}:block_info],...}) =
  532.           (pop_bottom_delim_stack dstack;
  533.            Block_size := INFINITY)
  534.       | set (_,BB {Ublocks = ref(_::rst), ...}) = fnl rst
  535.       | set (dstack, E{Pend,Uend}) =
  536.           (Pend := (!Pend) + (!Uend);
  537.            Uend := 0;
  538.            pop_bottom_delim_stack dstack)
  539.       | set (dstack,BR{Distance_to_next_break,...}) =
  540.           (pop_bottom_delim_stack dstack;
  541.            Distance_to_next_break := INFINITY)
  542.           | set _ = raise (Fail "PP-error: add_string.set")
  543.  
  544.     fun check_stream () =
  545.         if ((!right_sum - !left_sum) > !space_left)
  546.         then if (delim_stack_is_empty the_delim_stack)
  547.          then ()
  548.          else let val i = bottom_delim_stack the_delim_stack
  549.                in if (!left_index = i)
  550.               then set (the_delim_stack, the_token_buffer sub i)
  551.               else ();
  552.               advance_left(ppstrm,
  553.                                        the_token_buffer sub (!left_index));
  554.                   if (pointers_coincide ppstrm)
  555.                   then ()
  556.                   else check_stream ()
  557.               end
  558.         else ()
  559.  
  560.     val slen = String.size s
  561.     val S_token = S{String = s, Length = slen}
  562.  
  563.     in if (delim_stack_is_empty the_delim_stack)
  564.        then print_token(ppstrm,S_token)
  565.        else (++right_index;
  566.              update(the_token_buffer, !right_index, S_token);
  567.              right_sum := (!right_sum)+slen;
  568.              check_stream ())
  569.    end
  570.  
  571.  
  572. (* Derived form. The +2 is for peace of mind *)
  573. fun add_newline (pps : ppstream) =
  574.   let val PPS{linewidth, ...} = magic pps
  575.   in add_break pps (linewidth+2,0) end
  576.  
  577. (* Derived form. Builds a ppstream, sends pretty printing commands called in
  578.    f to the ppstream, then flushes ppstream.
  579. *)
  580.  
  581. fun with_pp ppconsumer ppfn =
  582.    let val ppstrm = mk_ppstream ppconsumer
  583.     in ppfn ppstrm;
  584.        flush_ppstream0 ppstrm
  585.    end
  586.    handle Fail msg =>
  587.      (TextIO.print (">>>> Pretty-printer failure: " ^ msg ^ "\n"))
  588.  
  589. fun pp_to_string linewidth ppfn ob =
  590.     let val l = ref ([]:string list)
  591.     fun attach s = l := (s::(!l))
  592.      in with_pp {consumer = attach, linewidth=linewidth, flush = fn()=>()}
  593.         (fn ppstrm =>  ppfn ppstrm ob);
  594.     String.concat(List.rev(!l))
  595.     end
  596.